﻿using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

namespace Framework
{
    public class RemoteResLoader : ResLoader
    {
        private UnityWebRequest _request;
        private Coroutine _coroutine;
        
        public RemoteResLoader(Resource resource) : base(resource)
        {
        }

        protected override void OnStart()
        {
            _coroutine = Scheduler.Instance.StartCoroutine(SendWebRequest()); 
        }

        protected override void OnCancel()
        {
            if (_coroutine != null)
            {
                Scheduler.Instance.StopCoroutine(_coroutine);
                _coroutine = null;
                _request.Dispose();
                _request = null;
            }
        }
        
        private IEnumerator SendWebRequest()
        {
            _request = new UnityWebRequest(resource.url);
            _request.downloadHandler = CreateDownloadHandler(resource);
            yield return _request.SendWebRequest();
            _coroutine = null;
            if (string.IsNullOrEmpty(_request.error))
            {
                switch (resource.assetType)
                {
                    case AssetType.AssetBundle:
                        OnSuccess((_request.downloadHandler as DownloadHandlerAssetBundle).assetBundle);
                        break;
                    case AssetType.Texture:
                        OnSuccess((_request.downloadHandler as DownloadHandlerTexture).texture);
                        break;
                    case AssetType.AudioClip:
                        OnSuccess((_request.downloadHandler as DownloadHandlerAudioClip).audioClip);
                        break;
                    case AssetType.Text:
                        OnSuccess(_request.downloadHandler.text);
                        break;
                    default:
                        OnSuccess(_request.downloadHandler.data);
                        break;
                }
                _request.Dispose();
                _request = null;
            }
            else
            {
                string error = _request.error;
                _request.Dispose();
                _request = null;
                OnFail(error);
            }
        }
        
        private DownloadHandler CreateDownloadHandler(Resource resource)
        {
            switch (resource.assetType)
            {
                case AssetType.AssetBundle:
                    return new DownloadHandlerAssetBundle(resource.url, 0);
                case AssetType.Texture:
                    return new DownloadHandlerTexture();
                case AssetType.AudioClip:
                    return new DownloadHandlerAudioClip(resource.url, AudioType.MPEG);
                default:
                    return new DownloadHandlerBuffer();
            }
        }
    }
}